package com.kavin.zxingutils;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.kavin.zxing.ScanResult;
import com.kavin.zxing.ZxingUtils;

import java.io.UnsupportedEncodingException;

public class MainActivity extends AppCompatActivity {

    private ImageView imageView;
    private EditText et;
    private TextView scan_content;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = findViewById(R.id.image);
        et = findViewById(R.id.et);
        scan_content = findViewById(R.id.scan_content);

    }

    public void click(View view) {
        //String content = "你好，我的世界！";
        String content = et.getText().toString();
        try {
            //解决中文乱码
            content = new String(content.getBytes("UTF-8"), "iso-8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Bitmap qrCode = ZxingUtils.createQRCode(content);
        imageView.setImageBitmap(qrCode);
    }

    public void scan(View view) {
        ZxingUtils.scan(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 获取解析结果
        ScanResult scanResult = ZxingUtils.parseScanResult(requestCode, resultCode, data);
        if (scanResult != null) {
            if (scanResult.getContents() == null) {
                Toast.makeText(this, "取消扫描", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this, "扫描内容:" + scanResult.getContents(), Toast.LENGTH_LONG).show();
                scan_content.setText(scanResult.getContents());
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }
}
